package com.boot.main.config.configDemo;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
// 面向切面编程
@Aspect
@Component
public class MemAopService {
    @Pointcut("execution(* com.boot.main.controller.*.*(..))")
    private void checkMem() {}
    @Before("checkMem()")
    private void before(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        System.out.println("1Url is:" + request.getRequestURL().toString());
//        System.out.println("1method is:" + joinPoint.getSignature().getName());
    }
    @After("checkMem()")
    private void printMem(){
//        System.out.println("3After the method, is Mem usage is:" + Runtime.getRuntime().freeMemory()/1024/1024 + "M");
    }
    @Around("checkMem()")
    private Object around(ProceedingJoinPoint joinPoint) throws Throwable{
//        System.out.println("2Around for Aop");
        Object[] args = joinPoint.getArgs();
        Object ret = joinPoint.proceed(args);

//        System.out.println("2proceed args, result is: " + args);
//        System.out.println("2proceed args, result is: " + ret);
        return ret;
    }
    @AfterReturning(pointcut="checkMem()", returning = "returnObj")
    private void afterReturning(Object returnObj){
//        System.out.println("4return value is:" + returnObj);
    }
    @AfterThrowing(pointcut = "checkMem()", throwing= "e")
    private void afterThrowing(JoinPoint joinPoint, Exception e){
//        System.out.println("5Exception is:" + e.getMessage());
    }
}
